<template>
  <div>
    <top-bar></top-bar>
    <left-bar :datas='data'></left-bar>
    <div class="adddrug system">
      <home-bar :currentPage='currentPage'></home-bar>
      <div class="adddrugs system-main">
        <div class="main-position">
          首页 > 商城管理 > 店铺管理
        </div>
        <div class="main-height"></div>
        <div class="main-mains">
          <div class="main-top-nav">
            <ul>
              <li :class="{active: this.$route.params.id == 'pc'}">
                <router-link to="/mallstoremgmt/pc" @click.native="addPath('/mallstoremgmt/pc','商城管理'); determineRouting('pc')">
                  店铺管理(pc)
                </router-link>
              </li>
              <li :class="{active: this.$route.params.id == 'sj'}">
                <router-link to="/mallstoremgmt/sj" @click.native="addPath('/mallstoremgmt/sj','商城管理'); determineRouting('sj')">
                  店铺管理(sj)
                </router-link>
              </li>
              <li v-for="(item, index) in specialFieldList" :key="index">
                <router-link :to='"/mallproductmgmt/"+item.id' @click.native="addPath('/mallproductmgmt/'+item.id,'商城管理');">
                  {{item.name}}
                </router-link>
              </li>
            </ul>
          </div>
          <div class="drugListMain">
            <div class="headOperation">
              <el-button  size="medium"  @click="addBanner(1)">添加宣传</el-button>
            </div>
            <!--/.headOperation -->
            <div class="drugListTable">
              <table>
                <tr>
                  <td>
                    序号
                  </td>
                  <td>缩略图</td>
                  <td>活动描述</td>
                  <td>状态</td>
                  <td>操作</td>
                </tr>
                <tr v-for="(item,index) in banner_list" :key="index">
                  <td>{{index+1}}</td>
                  <td width="600">
                    <img :src="item.image_url" alt="" class="trBannerImg">
                  </td>
                  <td>{{item.description}}</td>
                  <td>{{item.status | filterStatus}}</td>
                  <td>
                    <el-tooltip placement="left" v-if="item.status != 3">
                      <div slot="content">编辑</div>
                      <el-button><i class="iconfont icon-bianji" @click="addBanner(2,item.id,item.description,item.image_url)"></i></el-button>
                    </el-tooltip>
                    <el-tooltip placement="left" v-if="item.status == 1">
                      <div slot="content">下架</div>
                      <el-button><i class="iconfont icon-xiajia" @click="changeStatusFun(2,item.id,item.description)"></i></el-button>
                    </el-tooltip>
                    <el-tooltip placement="left" v-if="item.status == 2">
                      <div slot="content">上架</div>
                      <el-button><i class="iconfont icon-shangjia" @click="changeStatusFun(1,item.id,item.description)"></i></el-button>
                    </el-tooltip>
                    <el-tooltip placement="left" v-if="item.status != 3">
                      <div slot="content">删除</div>
                      <el-button><i class="iconfont icon-shanchu" @click="changeStatusFun(3,item.id,item.description)"></i></el-button>
                    </el-tooltip>
                  </td>
                </tr>
              </table>
            </div>
            <div class="pageBotom">
              <div class="pageBotomRight">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="currentPage4" :page-size="20" layout="total, prev, pager, next" :total="totalNumOfArticle">
                </el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 弹窗开始 -->
      <div class="system-menban" v-show="showSystemPopup"></div>
      <div class="systemPopup" v-show="showSystemPopup">
        <div class="topTitle">
          <span>{{systemPopupTitle}}</span>
          <i class="el-icon-close system-icon" @click="hideSystemPopup"></i>
        </div>
        <!-- 添加专题弹窗 -->
        <div class="addBannerPupup" v-if="showAddBannerPupup">
          <div class="bannerContent clear">
            <span class="leftTitle">轮播图</span>
            <div class="rightContent">
              <label class="chooseBanner" for="uploads">选择图片</label>
              <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/jpg" @change="uploadImg($event)">
            </div>
          </div>
          <div class="bannerContent clear">
            <span class="leftTitle">缩略图</span>
            <div class="rightContent">
              <vueCropper ref="cropper3" :img="example3.img" :outputSize="example3.outputSize" :canMoveBox="example3.canMoveBox" :canMove="example3.canMove" :autoCrop="example3.autoCrop" :autoCropWidth="example3.autoCropWidth" :autoCropHeight="example3.autoCropHeight"
                :fixedBox="example3.fixedBox" :canScale="example3.canScale">
              </vueCropper>
              <span v-if="pageType == 1">图片尺寸为1920*350像素</span>
              <span v-else-if="pageType == 2">图片尺寸为726*320像素</span>
            </div>
          </div>
          <div class="bannerContent clear">
            <span class="leftTitle">活动描述</span>
            <div class="rightContent">
              <el-input v-model="description" placeholder="请输入活动描述"></el-input>
            </div>
          </div>
          <div class="system-messagebox1-btn clear">
            <div @click="determineAddBrand">添加</div>
            <div @click="hideSystemPopup">取消</div>
          </div>
        </div>
      </div>
      <!-- 弹窗结束 -->
    </div>
  </div>
</template>

<script>
  import topBar from "../../public/top";
  import leftBar from "../../public/left";
  import homeBar from "../../public/homebar";
  import vueCropper from "vue-cropper";
  export default {
    components: {
      leftBar,
      topBar,
      homeBar,
      vueCropper
    },
    data() {
      return {
        data: "mallMgmt",
        currentPage: {
          path: "/mallstoremgmt",
          name: "商城管理"
        },
        showSystemPopup: false,
        systemPopupTitle: "",
        showAddBannerPupup: false, //添加宣传 （开关）
        banner_list: [],
        currentPage4: 1,
        pageType: 1, //1是pc 2是手机
        showPageNum: 1, //要展示的页展示的页码
        totalNumOfArticle: 1,
        example3: {
          img: "http://p5vegqhl6.bkt.clouddn.com/2018_04_28_14_40_09_FKmi3j7LdaxWSl8TuFOYmUjlC9DzwbDq.jpg",
          autoCrop: false,
          canScale: false,
          fixedBox: true,
          canMove: true,
          canMoveBox: false,
          outputSize: 0.8
        },
        description: "", //活动描述
        editType: 1, //1为新增  2为编辑
        itemId: "", //专题id
        itemImage_url: "", //专题图片
        specialFieldList:"",
      };
    },
    activated() {
      //页面加载完判断路由
      const routeParamsId = this.$route.params.id;
      if (routeParamsId == "pc") {
        this.pageType = 1;
      } else if (routeParamsId == "sj") {
        this.pageType = 2;
      }
      this.getSpecialFieldList();
      this.getBannerList();
    },
    methods: {
      //点击导航时判断路由
      determineRouting(obj) {
        if (obj == "pc") {
          this.pageType = 1;
        } else if (obj == "sj") {
          this.pageType = 2;
        }
        this.getBannerList();
      },
      //错误弹窗
      messageAlert(msg) {
        this.$message.error(msg);
      },
      //成功弹窗
      successfulAlert(msg) {
        this.$message({
          message: msg,
          type: 'success'
        });
      },
      //提示框
      infoAlert(msg) {
        this.$message(msg);
      },
      //获取专题列表
      getBannerList() {
        let _this = this;
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        _this
          .$http({
            url: this.urls +
              "/who/market/getBannerList/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token") + "?page=" + this.showPageNum + "&type=" + this.pageType,
            method: "get"
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
              _this.banner_list = data.data.banner_list;
              _this.totalNumOfArticle = data.data.total;
              localStorage.setItem("nowTimes", new Date().getTime() / 1000);
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      //修改专题状态
      changeStatusFun(status, id, desc) {
        var tipText = "";
        if (status == 1) {
          tipText = "上架"
        } else if (status == 2) {
          tipText = "下架"
        } else if (status == 3) {
          tipText = "删除"
        }
        this.$confirm('是否要' + tipText + ":" + desc, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.sureChangeStatusFun(status, id);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消' + tipText
          });
        });
      },
      //点击确认修改状态
      sureChangeStatusFun(status, id) {
        let _this = this;
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        _this
          .$http({
            url: this.urls +
              "/who/market/changeBannerStatus/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token"),
            method: "post",
            data: {
              banner_id: id,
              status: status
            }
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
              _this.getBannerList();
              localStorage.setItem("nowTimes", new Date().getTime() / 1000);
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      //获取专场列表(导航)
      getSpecialFieldList() {
        let _this = this;
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        _this
          .$http({
            url: this.urls +
              "/who/market/getSpecialFieldList/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token"),
            method: "get"
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
             _this.specialFieldList = data.data.special_field_list;
              localStorage.setItem("nowTimes", new Date().getTime() / 1000);
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      finish() {
        // 裁剪
        let _this = this;
        _this.$refs.cropper3.getCropData(data => {
          _this.example3.img = data;
        });
      },
      uploadImg(e) {
        var file = e.target.files[0];
        if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
          alert("图片类型必须是jpeg,jpg,png中的一种");
          return false;
        }
        var reader = new FileReader();
        // 转化为base64
        reader.onload = e => {
          this.example3.img = e.target.result;
        };
        reader.readAsDataURL(file);
      },
      //点击添加专题
      addBanner(editType, id, description, image_url) {
        this.showSystemPopup = true; //弹窗总开关
        this.showAddBannerPupup = true; //添加专题 （开关）
        this.systemPopupTitle = "添加专题"; //标题
        this.editType = editType;
        if (editType == 2) {
          this.itemId = id;
          this.description = description;
          this.example3.img = image_url;
          this.itemImage_url = image_url;
        }
      },
      //点击确定添加专题
      determineAddBrand() {
        let _this = this;
        if (this.editType == 1) { //添加专题
          _this
            .$http({
              url: _this.urls +
                "/who/market/addBanner/" +
                localStorage.getItem("uid") +
                "/" +
                localStorage.getItem("token"),
              method: "post",
              data: {
                type: _this.pageType,
                description: _this.description,
                image: _this.example3.img
              }
            })
            .then(function(res) {
              let data = res.data;
              if (data.code == "1") {
                _this.successfulAlert("添加成功!");
                _this.hideSystemPopup();
                _this.getBannerList();
              } else {
                _this.messageAlert(data.msg)
              }
            })
            .catch(function(error) {
              console.log(error);
            });
        } else if (this.editType == 2) { //编辑专题
          var image = "";
          if (this.example3.img != this.itemImage_url) {
            image = this.example3.img;
          }
          _this
            .$http({
              url: _this.urls +
                "/who/market/editBanner/" +
                localStorage.getItem("uid") +
                "/" +
                localStorage.getItem("token"),
              method: "post",
              data: {
                banner_id:_this.itemId,
                type: _this.pageType,
                description: _this.description,
                image: _this.example3.img
              }
            })
            .then(function(res) {
              let data = res.data;
              if (data.code == "1") {
                _this.successfulAlert("编辑成功!");
                _this.hideSystemPopup();
                _this.getBannerList();
              } else {
                _this.messageAlert(data.msg)
              }
            })
            .catch(function(error) {
              console.log(error);
            });
        }
      },
      hideSystemPopup() {
        //关闭弹窗
        this.showSystemPopup = false;
        this.systemPopupTitle = "";
        this.example3.src = "http://p5vegqhl6.bkt.clouddn.com/2018_04_28_14_40_09_FKmi3j7LdaxWSl8TuFOYmUjlC9DzwbDq.jpg";
        this.description = "";
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        this.showPageNum = val;
        this.getBannerList();
      },
      addPath(n1, n2) {
        //点击切换home-bar
        var obj = {};
        obj.n1 = n1;
        obj.n2 = n2;
        this.$store.commit("addPath", obj);
      }
    },
    filters: {
      filterStatus(value) {
        let types;
        if (value == 1) {
          types = '已上架'
        } else if (value == 2) {
          types = '已下架'
        } else if (value == 3) {
          types = '已删除'
        }
        return types;
      }
    }
  };
</script>

<style lang="less">
  @import "../css/mallList.less";
</style>
